package com.test.mchelepesa.util_rice;

import android.os.Handler;
import android.os.Looper;

import com.test.mchelepesa.constant_rice.Constant_rice;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadUtil_rice {

    private final ExecutorService cachedThreadPool;
    private final Handler handler;

    private static class Inner {
        private static final ThreadUtil_rice INSTANCE = new ThreadUtil_rice();
    }

    private ThreadUtil_rice() {
        int cpuCount = Runtime.getRuntime().availableProcessors();
        int calculatedMax = cpuCount * 2 + 1;
        int maxPoolSize = Math.min(20, calculatedMax);

        cachedThreadPool = new ThreadPoolExecutor(
                0,
                maxPoolSize,
                60L,
                TimeUnit.SECONDS,
                new SynchronousQueue<>()
        );

        handler = new Handler(Looper.getMainLooper());
    }

    public static ThreadUtil_rice getInstance() {
        return Inner.INSTANCE;
    }

    public void runOnChildThread(Runnable runnable) {
        if (Looper.getMainLooper().isCurrentThread()) {
            // 当前是主线程，切换到子线程执行
            cachedThreadPool.execute(() -> {
                try {
                    runnable.run();
                } catch (Exception e) {
                    // StringUtil_rice.printException(e);
                }
            });
        } else {
            // 当前已经是子线程，直接执行
            try {
                runnable.run();
            } catch (Exception e) {
                // StringUtil_rice.printException(e);
            }
        }
    }

    public void runOnUiThread(Runnable runnable) {
        if (Looper.getMainLooper().isCurrentThread()) {
            // 当前是主线程，直接执行
            try {
                runnable.run();
            } catch (Exception e) {
                StringUtil_rice.printException(e);
            }
        } else {
            // 当前已经是子线程，切换到主线程执行
            handler.post(() -> {
                try {
                    runnable.run();
                } catch (Exception e) {
                    StringUtil_rice.printException(e);
                }
            });
        }
    }

    public void postDelay(Runnable runnable, long delayMillis) {
        handler.postDelayed(() -> {
            try {
                runnable.run();
            } catch (Exception e) {
                // StringUtil_rice.printException(e);
            }
        }, delayMillis);
    }

}
